/**
 * @author Rid King
 * @since 2017-06-02
 * @version 2.0.0
 * @description 过虑操作符
 */
'user strict';

import Operator from '../operator.js'

/**
 * @description 过滤操作，判断不通过则不继续执行
*/
class FilterOperator extends Operator{
    /**
     * @description 获取操作名称
     * @return <String>
    */
    static getName () {
        return 'filter'
    }

    /**
     * @function 操作处理逻辑
     * [@param fn <Function> 过滤方法]
    */
    process (fn) {
        super.process.apply(this, arguments)

        // 过滤方法处理，默认全部通过
        let filter = this._args[0]
        filter = typeof filter === 'function' ? filter : function () {return true}

        // 重新设置下一步操作
        let next = this.destination.next
        let error = this.destination.error
        this.destination.next = function () {
            try {
                // 返回值为true时执行下一步
                if (filter.apply(this, arguments) === true) {
                    typeof next === 'function' && next.apply(this.destination, arguments)
                }
            }
            catch (e) {
                typeof error === 'function' && error.apply(this.destination, arguments)
            }
        }
    }
}

export default FilterOperator